package SearchTree;

import java.io.FileInputStream;
import java.io.IOException;


public class SearchTreeLoader {

	private int offset;
	private int length;
	private SearchNodeReader reader;
	
	public void Import(String fileName) {
		byte[] idxData = null;
		try {
			FileInputStream idxFile = new FileInputStream(fileName);
			idxData = new byte[idxFile.available()];
			idxFile.read(idxData);
			idxFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		reader = new SearchNodeReader(idxData);
	}
	
	public boolean Find(String index) {
		reader.Reset();
		for(int i=0; i<index.length(); ++i) {
			if(!FindMatchNode(index.charAt(i))) {
				return false;
			}
			if(i+1 < index.length() && !reader.GotoChild()) {
				return false;
			}
		}
		if(reader.IsFinishNode()) {
			offset = reader.ReadInt();
			length = reader.ReadInt();
			return true;
		}
		return false;
	}
	
	public int GetOffset() {
		return offset;
	}
	
	public int GetLength() {
		return length;
	}
	
	private boolean FindMatchNode(char c) {
		char key;
		while((key = reader.ReadNode()) < c) {
			if(!reader.GotoBrother()) {
				return false;
			}
		}
		return key == c;
	}
	
	public static void main(String args[]) {
		SearchTreeLoader t = new SearchTreeLoader();
		t.Import("Index");
		t.Find("testament");
	}	
}
